package com.smartpower.wattmeter.ui;

import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.android.basiclib.base.BaseActivity;
import com.android.basiclib.uitls.CheckUtil;
import com.android.basiclib.uitls.CommUtils;
import com.android.basiclib.uitls.Log.LogUtil;
import com.android.basiclib.uitls.NetWorkUtil;
import com.android.basiclib.uitls.ToastUtils;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.bikenavi.BikeNavigateHelper;
import com.baidu.mapapi.bikenavi.adapter.IBEngineInitListener;
import com.baidu.mapapi.bikenavi.adapter.IBRoutePlanListener;
import com.baidu.mapapi.bikenavi.model.BikeRoutePlanError;
import com.baidu.mapapi.bikenavi.params.BikeNaviLaunchParam;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;

import com.baidu.mapapi.search.route.BikingRoutePlanOption;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.smartpower.wattmeter.R;
import com.smartpower.wattmeter.utils.BikingRouteOverlay;
import com.smartpower.wattmeter.utils.DrivingRouteOverlay;

/**
 * 工单详情-地图页面
 */
public class OrderDetailActivity extends BaseActivity implements View.OnClickListener {

    private com.baidu.mapapi.map.MapView mMapView;
    private BaiduMap mBaiduMap;
    private LocationClient mLocationClient;
    private boolean isMovedMyLocation = false;
    private RoutePlanSearch mRouteSearch;
    private LatLng mMyLatLng;
    private android.widget.TextView mTvTitle;
    private android.widget.TextView mTvAddress;
    private android.widget.ImageView mIvNavigationIcon;
    private android.widget.ImageView mIvBack;

    public static void startInstance() {
        Context context = CommUtils.getContext();
        Intent intent = new Intent(context, OrderDetailActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutResId() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        return R.layout.activity_order_detail;
    }

    @Override
    protected void init() {
        initView();
        //初始化百度地图的初始位置和状态
        initBaiduMap();
        initListener();
    }

    private void initListener() {
        mIvBack.setOnClickListener(this);
        mIvNavigationIcon.setOnClickListener(this);
    }

    //开启导航
    private void navigate2Location() {

        // 获取导航控制类
        BikeNavigateHelper.getInstance().initNaviEngine(this, new IBEngineInitListener() {
            @Override
            public void engineInitSuccess() {
                //骑行导航初始化成功之后的回调
                LogUtil.w("骑行导航初始化成功");

                //起终点位置
                LatLng endPt = new LatLng(30.61548699999999, 114.254961);
                //构造BikeNaviLaunchParam
                //.vehicle(0)默认的普通骑行导航
                BikeNaviLaunchParam param = new BikeNaviLaunchParam().stPt(mMyLatLng).endPt(endPt).vehicle(0);

                //发起算路
                BikeNavigateHelper.getInstance().routePlanWithParams(param, new IBRoutePlanListener() {
                    @Override
                    public void onRoutePlanStart() {
                        //执行算路开始的逻辑
                    }

                    @Override
                    public void onRoutePlanSuccess() {
                        //算路成功
                        //跳转至导航页面
                        Intent intent = new Intent(mActivity, BNaviGuideActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onRoutePlanFail(BikeRoutePlanError bikeRoutePlanError) {
                        //执行算路失败的逻辑
                        ToastUtils.makeText(mActivity, "规划导航路径失败：" + bikeRoutePlanError.toString());
                    }
                });
            }

            @Override
            public void engineInitFail() {
                //骑行导航初始化失败之后的回调
                LogUtil.w("骑行导航初始化失败");
            }
        });

    }

    //路线规划
    private void initTTS() {
        mRouteSearch = RoutePlanSearch.newInstance();
        mRouteSearch.setOnGetRoutePlanResultListener(listener);

        PlanNode stNode = PlanNode.withLocation(mMyLatLng);
        PlanNode enNode = PlanNode.withLocation(new LatLng(30.61548699999999, 114.254961));
        mRouteSearch.bikingSearch((new BikingRoutePlanOption())
                .from(stNode)
                .to(enNode));
    }

    private void initBaiduMap() {

        //获取地图控制器
        mBaiduMap = mMapView.getMap();

        //隐藏比例按钮：隐藏缩放按钮
        mMapView.showScaleControl(false);
        mMapView.showZoomControls(false);

        //改变缩放值到17
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomTo(17));
        //获取UI控制器，隐藏指南针：
        UiSettings uiSettings = mBaiduMap.getUiSettings();
        //不显示指南针
        uiSettings.setCompassEnabled(false);

        //设置自己的定位点的 模式-方向-icon
        MyLocationConfiguration configuration = new MyLocationConfiguration(
                MyLocationConfiguration.LocationMode.NORMAL, true, null
        );
        mBaiduMap.setMyLocationConfiguration(configuration);
        mBaiduMap.setMyLocationEnabled(true);

        //自己位置的定位初始化
        mLocationClient = new LocationClient(this);

        //通过LocationClientOption设置LocationClient相关参数
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);

        //设置locationClientOption
        mLocationClient.setLocOption(option);

        //注册LocationListener监听器
        MyLocationListener myLocationListener = new MyLocationListener();
        mLocationClient.registerLocationListener(myLocationListener);
        //开启地图定位图层
        mLocationClient.start();
    }

    @Override
    public void onNetworkConnectionChanged(boolean isConnected, NetWorkUtil.NetworkType networkType) {
    }

    @Override
    protected void dataObserver() {

    }

    private void initView() {
        mMapView = findViewById(R.id.bmapView);
        mTvTitle = findViewById(R.id.tv_title);
        mTvAddress = findViewById(R.id.tv_address);
        mIvNavigationIcon = findViewById(R.id.iv_navigation_icon);
        mIvBack = findViewById(R.id.iv_back);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.iv_back:
                mActivity.finish();
                break;
            case R.id.iv_navigation_icon:
                if (mMyLatLng != null) {
                    navigate2Location();
                }
                break;

        }
    }

    /**
     * 百度地图位置更新
     */
    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
//            LogUtil.e("获取到自己的位置信息：" + location.toString());
            //mapView 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }

            mMyLatLng = new LatLng(location.getLatitude(), location.getLongitude());
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(location.getDirection())
                    .latitude(location.getLatitude())
                    .longitude(location.getLongitude())
                    .build();

            mBaiduMap.setMyLocationData(locData);

            if (!isMovedMyLocation) {
                //移动相机到指定的经纬度,只是第一次移动
                isMovedMyLocation = true;
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(new LatLng(location.getLatitude(), location.getLongitude())).zoom(17.0f);
                mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));

                //初始化路线规划
                initTTS();
            }


            //添加指定的覆盖物
//            BitmapDescriptor searchBdA = BitmapDescriptorFactory.fromResource(R.drawable.ico_search);
//            MarkerOptions option = new MarkerOptions().icon(searchBdA).position(latLng);
//            mBaiduMap.addOverlay(option);

        }
    }

    /**
     * 路径规划的回调
     */
    OnGetRoutePlanResultListener listener = new OnGetRoutePlanResultListener() {

        @Override
        public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {
        }

        @Override
        public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {
        }

        @Override
        public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {
        }

        @Override
        public void onGetDrivingRouteResult(DrivingRouteResult drivingRouteResult) {
            //创建DrivingRouteOverlay实例
            DrivingRouteOverlay overlay = new DrivingRouteOverlay(mBaiduMap);
            if (drivingRouteResult != null && drivingRouteResult.getRouteLines().size() > 0) {
                //获取路径规划数据,(以返回的第一条路线为例）
                //为DrivingRouteOverlay实例设置数据
                overlay.setData(drivingRouteResult.getRouteLines().get(0));
                //在地图上绘制DrivingRouteOverlay
                overlay.addToMap();
            }
        }

        @Override
        public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {
        }

        @Override
        public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {

            if (bikingRouteResult != null && !CheckUtil.isEmpty(bikingRouteResult.getRouteLines())) {
                BikingRouteOverlay overlay = new BikingRouteOverlay(mBaiduMap);
                //获取路径规划数据,(以返回的第一条路线为例）
                //为DrivingRouteOverlay实例设置数据
                overlay.setData(bikingRouteResult.getRouteLines().get(0));
                //在地图上绘制DrivingRouteOverlay
                overlay.addToMap();
            }
        }

    };

    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        mLocationClient.stop();
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;
        super.onDestroy();

        if (mRouteSearch != null)
            mRouteSearch.destroy();
    }
}
